// popup.js

document.addEventListener('DOMContentLoaded', function() {

  // 获取DOM信息按钮
  const domButton = document.getElementById('domButton');
  const resultDiv = document.getElementById('result');

  domButton.addEventListener('click', async () => {
    
    try{
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

      // 向页面注入脚本并执行
      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: () => {
          // 找到左侧的显示区域
          let elems = document.querySelectorAll('.ds-scroll-area');
          if(elems.length < 2){
            return {success: false};
          }

          // 删除所有有cyf class的div
          let cyfDivs = document.querySelectorAll('div.cyf');
          for(let cyfDiv of cyfDivs){
            cyfDiv.remove();
          }

          let target = elems[1].querySelector('div:nth-child(1)');

          // 创建新的div元素，并插入第一个
          let newDiv = document.createElement('div');
          newDiv.className = 'cyf'
          target.insertBefore(newDiv, target.firstChild);

          // 找到所有message，特征：第二个class是ds-message
          let allElements = document.querySelectorAll('.ds-message');
          let messages = Array.from(allElements).filter(element => {
              classList = element.classList;
              return classList.length >= 2 && classList[1] === 'ds-message';
          });

          // 循环每个message
          for(let [index, messdiv] of messages.entries()){
              let messtextdiv = messdiv.querySelector('div:nth-child(1)');
              let messtext = messtextdiv.textContent;
              
              // 将文本内容，加入targetfirst
              let newmessdiv = document.createElement('p');
              newmessdiv.innerText = '[' + (index+1) + ']---\n' + messtext;
              newDiv.appendChild(newmessdiv);
              
              // 增加点击事件
              newmessdiv.addEventListener('click', function() {
                  messdiv.scrollIntoView(true); // 平滑滚动
              });
          }

          newDiv.scrollIntoView({behavior: 'smooth', block: 'end'}); // 动态滚动
          return {success: true};
        }
      });

      resultDiv.textContent = 'Unknown State';
      if(results && results[0] && results[0].result && results[0].result.success){
        resultDiv.textContent = 'Done';
      }else{
        resultDiv.textContent = 'Skip: Not DeepSeek Page';
      }

    } catch (error) {
      resultDiv.textContent = 'Error: ' + error.message;
    }

  });   // addEventListener('click'
})      // addEventListener('DOMContentLoaded'
